//
//  MYGSelectUserController.swift
//  MYGrow
//
//  Created by 林矗 on 2024/4/14.
//

import UIKit

class MYGSelectUserController: MYGBaseController {
    // MARK: - Property
    var indexArray = [String]()
    var model = [MYGPatientList]()
    var sortedNameDict = [String:[MYGPatientList]]()
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "我的患者"
        view.addSubview(serachBView)
        serachBView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(23)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(35)
        }
        
        serachBView.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(11)
            make.right.equalToSuperview().offset(-11)
            make.top.bottom.equalToSuperview()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(serachBView.snp.bottom).offset(10)
            make.left.right.bottom.equalToSuperview()
        }
        
        refresh()
    }
    

    @objc func refresh() {
        MYGLoading.show()
        let parms = ["name":self.searchTextField.text ?? ""]
         MYGNetwork<MYGPatientImageApi, MYGPageModel<MYGPatientList>>.request(target: .myPatients(params: parms)) {[weak self] item in
             self?.model = item.list
             self?.configDataSource()
             MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func configDataSource() {
        self.indexArray.removeAll()
        self.sortedNameDict.removeAll()
        for(_,obj) in self.model.enumerated() {
            self.indexArray.append(obj.patient.name.getFirstLetter())
        }
        self.indexArray = self.indexArray.uniqued{$0}
        for (_,obj) in self.indexArray.enumerated() {
            var dataArray = [MYGPatientList]()
            for(_,data) in self.model.enumerated() {
                if data.patient.name.getFirstLetter() == obj {
                    dataArray.append(data)
                }
            }
            self.sortedNameDict[obj] = dataArray
        }
        self.tableView.reloadData()
    }
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 70
        tableView.register(cellWithClass: MYGSelectUserCell.self)
        return tableView
    }()
    
    lazy var searchTextField: UITextField = {
        let control = UITextField()
        control.textAlignment = .center
        control.placeholder = "搜索"
        control.delegate = self
        control.clearButtonMode = .whileEditing
        control.returnKeyType = .search
        return control
    }()
    
    var serachBView: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F5F5F5")
        control.addCorner(radius: 17.5)
        return control
    }()
    
}

extension MYGSelectUserController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGSelectUserCell", for: indexPath) as! MYGSelectUserCell
        if let model = self.sortedNameDict[self.indexArray[indexPath.section]]?[indexPath.row] {
            cell.model = model
        }
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.sortedNameDict.keys.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sortedNameDict[self.indexArray[section]]?.count ?? 0
    }
    
      func sectionIndexTitles(for tableView: UITableView) -> [String]? {
          return indexArray
      }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.indexArray[section]
    }

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let model = self.sortedNameDict[self.indexArray[indexPath.section]]?[indexPath.row] {
            let vc = MYGpatientImageListVC()
            vc.patientId = model.patient.id
            vc.patientName = model.patient.name
            self.navigationController?.pushViewController(vc)
        }
    }
}
extension MYGSelectUserController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        refresh()
        return true
    }
}
